<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\Product;
use App\Models\Order;
use App\Http\Resources\Front\Order as OrderResource;
use App\Http\Resources\Front\OrderCollection;
use App\Models\UserAddress;
use App\Models\ShopBalanceLog;
use Carbon\Carbon;
use DB;

class OrderController extends ApiController
{

    /**
     * 订单列表
     */
    public function index(Request $request) 
    {
        $limit = $request->input('size', 10);
        $status = $request->input('status', 'all');
        $type = $request->input('type');

        if ($type === 'sold') {
            $orderOrm = Order::ownerStore();
        } else {
            $orderOrm = Order::owner();
        }

        if($status && $status !== 'all') {
            $orderOrm->where('status', Order::getOrderStatus($status));
        }

        $orderOrm->orderBy('id', 'DESC')->with(['user' => function($query) {
            $query->select('id', 'name'); // 用户ID，名称
        }])->with(['shop' => function($query) {
            $query->select('id', 'name'); // 店铺ID，名称
        }])->with(['orderItems']);

        return new OrderCollection($orderOrm->paginate($limit));
    }

    /**
     * 获取指定订单
     */
    public function show($id, Request $request)
    {
        $type = $request->input('type');

        if ($type === 'sold') {
            $orderOrm = Order::ownerStore();
        } else {
            $orderOrm = Order::owner();
        }

        $order = $orderOrm->with(['orderItems'])
            ->with(['user' => function($query) {
                $query->select('id', 'name');
            }])  
            ->with(['shop' => function($query) {
                $query->select('id', 'name');
            }])
            ->find($id);

        return $this->success(new OrderResource($order));
    }


    /**
     * 处理订单创建
     */
    public function haddlecreate(Request $request)
    {
        $pid = $request->input('pid');  // 商品ID
        $aid = $request->input('aid');  // 地址ID
        $qyt = (int)$request->input('qty'); // 购买数量
        $message = $request->input('message'); // 留言
        
        // 查询该商品
        $product = Product::selling()->find($pid);
        if(!$product) {
            return $this->failed('商品不存在，或者已经下架');
        }

        // 查询地址
        if ($aid) {
            $address = useraddress::owner()->find($aid);
        } else {
            $address = useraddress::owner()->default()->first();
        }
        if(!$address) {
            return $this->failed('地址不存在');
        }

        if($qyt < 1) {
            return $this->failed('请输入购买数量');
        }

        $product_amount = number_format($product->price * $qyt, 2, '.', ''); // 商品总价

        // 创建订单
        DB::beginTransaction();

        $order = new Order();

        // 商品数量，总价
        $order->product_count = $qyt;
        $order->product_amount_total = $product_amount;
        $order->order_amount_total = $product_amount;

        // 店铺
        $order->shop_id = $product->shop->id;

        // 收货信息
        $order->contact_name = $address->contact_name;
        $order->contact_tel = $address->contact_tel;
        $order->area = $address->area;
        $order->address = $address->address;
        $order->buyer_message = $message;

        // 状态
        $order->status = Order::STATUS_UNPAID;

        $order->save();

        $order->orderItems()->createMany([
            [
                'product_id' => $product->id,
                'product_price' => $product->price,
                'product_count' => $qyt,
                'product_unit' => $product->unit,
                'product_name' => $product->name,
                'product_pic' => $product->cover_image,
                'product_info' => $product->cover_info,
                'product_spec' => $product->spec,
            ],
        ]);
        
        if ($order) {
            DB::commit();
            return $this->success($order->id);
        } else {
            DB::rollBack();
            return $this->failed($order->id);
        }
    }

    /**
     * 取消订单
     */
    public function cancle($id, Request $request)
    {
        $type = $request->input('type');
        if ($type === 'sold') {
            $orderOrm = Order::ownerStore();
        } else {
            $orderOrm = Order::owner();
        }

        $order = $orderOrm->find($id);

        if(!$order) {
            return $this->success('该订单不存在');
        }

        if(in_array($order->status, [0, -1])) {
            $order->status = 'cancelled';
            if($order->save()) {
                return $this->success('订单取消成功');
            }else {
                return $this->failed('订单取消失败');
            }
        }else {
            return $this->failed('该订单不允许取消');
        }

    }

    /**
     * 确认订单
     */
    public function confirm($id) {
        $order = Order::ownerStore()->find($id);

        if (in_array($order->status, [-1])) {
            $order->status = 'unpaid';
            if($order->save()) {
                return $this->success('订单确认成功');
            }else {
                return $this->failed('订单确认失败');
            }
        } else {
            return $this->failed('该订单不允许确认');
        }
    }

    /**
     * 发货确认
     */

    public function delivering($id) {
        $order = Order::ownerStore()->find($id);

        if (in_array($order->status, [1])) {
            $order->status = 'delivering';
            if($order->save()) {
                return $this->success('订单发货确认成功');
            }else {
                return $this->failed('订单发货确认失败');
            }
        } else {
            return $this->failed('该订单不允许发货确认');
        }
    }

    /**
     * 确认收货
     *
     * @return \Illuminate\Http\Response
     */
    public function receive($id)
    {
        $order = Order::Owner()->find($id);

        if ($order->status !== Order::STATUS_DELIVERING) {
            return $this->failed('确认收货失败');
        }

        $order->status = Order::STATUS_COMPLETED; 
        $order->completed_at = Carbon::now();

        if($order->save()) {
            $shop = $order->shop();
            $shop->balance + $order->order_amount_total;

            $shopBalanceLog = new ShopBalanceLog;
            $shopBalanceLog->shop_id = $order->shop_id;
            $shopBalanceLog->order_id = $order->order_id;
            $shopBalanceLog->invoice = $order->order_no;
            $shopBalanceLog->count = $order->order_amount_total;
            $shopBalanceLog->balance = $shop->balance;
            $shopBalanceLog->type = ShopBalanceLog::TYPE_ORDER;
            $shopBalanceLog->remark = '订单';

            $shopBalanceLog->save();

            return $this->success('确认收货成功');
        }else {
            return $this->success('确认收货失败');
        }

    }

    /**
     * 删除订单
     */
    public function destroy($id) {
        $order = Order::Owner()->find($id);
        if(in_array($order->status, [1, 2, 0])) {
            return $this->failed('不允许删除');
        }
        $order->delete();
        if($order->trashed()) {
            return $this->success('删除成功');
        }else {
            return $this->success('删除失败');
        }
    }
}
